package td3.model;

import java.awt.datatransfer.Transferable;

import javax.swing.JComponent;
import javax.swing.JTree;
import javax.swing.TransferHandler;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.TreePath;

public class ContactNodeTreeTransferHandler extends TransferHandler {

	private static final long serialVersionUID = 8807026538766261644L;

	@Override
	public boolean importData(TransferSupport support) {
		if (canImport(support)) {
			try {
				Transferable t = support.getTransferable();
				DefaultMutableTreeNode dmt = (DefaultMutableTreeNode) t
						.getTransferData(ContactNodeTransferable.nodeFlavor);
				JTree.DropLocation dl = (JTree.DropLocation) support
						.getDropLocation();
				TreePath tp = dl.getPath();
				if (tp == null) {
					return false;
				}
				DefaultMutableTreeNode parent = (DefaultMutableTreeNode) tp
						.getLastPathComponent();
				if (parent.getUserObject() instanceof Contact) {
					return false;
				}
				JTree tree = (JTree) support.getComponent();
				ContactTreeModel tm = (ContactTreeModel) tree.getModel();
				parent.add(dmt);
				tm.reload();
				tree.expandPath(tp);
				return true;
			} catch (Exception ex) {
				ex.printStackTrace();
			}
		}
		return false;
	}

	@Override
	public int getSourceActions(JComponent component) {
		return TransferHandler.MOVE;//COPY MOVE LINK
		
	}

	@Override
	public ContactNodeTransferable createTransferable(JComponent c) {
		DefaultMutableTreeNode node = null;
		if (c instanceof JTree) {
			try {
				TreePath path = ((JTree) c).getSelectionPath();
				node = (DefaultMutableTreeNode) path.getLastPathComponent();
			} catch (Exception e) {
				System.err
						.println("ContactTransferHanlder.createTransferable(JComponent) FAILED");
				e.printStackTrace();
			}
			return new ContactNodeTransferable(node);
		}
		return null;
	}

	@Override
	public boolean canImport(TransferHandler.TransferSupport support) {
		return support.isDrop()
				&& support.getTransferable().isDataFlavorSupported(
						ContactNodeTransferable.nodeFlavor);
	}

}
